<template>
  <div class="table2">
    <a-form label-align="right" layout="inline" auto-label-width :model="listParams" size="small" class="form mb-10">
      <a-form-item field="paymethod" label="打款账户">
        <a-cascader
          :options="payMethods1"
          :field-names="fieldNames"
          placeholder="请选择"
          v-model="listParams.payAccount"
          @change="changeCurrent(1)"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="payType" label="打款类型" :show-colon="false">
        <a-select
          placeholder="请选择"
          :style="{ minWidth: '200px' }"
          v-model="listParams.payType"
          @change="changeCurrent(1)"
          allow-clear
        >
          <a-option value="0">全部</a-option>
          <a-option value="1">支付宝</a-option>
          <a-option value="2">银行卡</a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="withdrawalType" label="提现类型" :show-colon="false">
        <a-select
          placeholder="请选择"
          :style="{ minWidth: '200px' }"
          v-model="listParams.withdrawalType"
          @change="changeCurrent(1)"
          allow-clear
        >
          <a-option value="0">全部</a-option>
          <a-option value="1">支付宝</a-option>
          <a-option value="4">灵工银行卡</a-option>
          <a-option value="3">灵工支付宝</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="提现时间" field="submitStartAt">
        <ms-date
          v-model:start="listParams.submitStartAt"
          v-model:end="listParams.submitStartEnd"
          :showQuick="true"
          @dateChange="topRefresh()"
        ></ms-date>
      </a-form-item>
      <a-form-item label="到账时间" field="payStartAt">
        <ms-date
          v-model:start="listParams.payStartAt"
          v-model:end="listParams.payStartEnd"
          :showQuick="true"
          @dateChange="topRefresh()"
        ></ms-date>
      </a-form-item>
      <a-form-item field="keyword" label="提现金额" :span="12">
        <a-input-number v-model="listParams.minAmount" :style="{ width: '120px' }" placeholder="0" /><span
          class="pl-10 pr-10"
          >至</span
        ><a-input-number v-model="listParams.maxAmount" :style="{ width: '120px' }" placeholder="0" />
      </a-form-item>

      <a-form-item field="status" label="状态">
        <a-select
          v-model="listParams.status"
          placeholder="选择状态检索"
          class="w-45n"
          @change="changeCurrent(1)"
          allow-clear
        >
          <a-option :value="item.id" :label="item.text" v-for="(item, index) in statusList" :key="index"></a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="withdrawalNo" hide-label>
        <a-input
          v-model="listParams.withdrawalNo"
          placeholder="输入提现订单号"
          @press-enter="changeCurrent(1)"
        ></a-input>
      </a-form-item>

      <a-form-item field="alipayTradeId" hide-label :span="12">
        <a-input
          v-model="listParams.alipayTradeId"
          placeholder="输入支付宝交易号"
          @press-enter="changeCurrent(1)"
        ></a-input>
      </a-form-item>

      <a-form-item field="keyword" hide-label>
        <a-input
          v-model="listParams.keyword"
          placeholder="输入邀请码/手机号"
          @press-enter="changeCurrent(1)"
        ></a-input> </a-form-item
      ><a-form-item field="receiveAccount" hide-label>
        <a-input
          v-model="listParams.receiveAccount"
          placeholder="输入支付宝账号/银行卡账号"
          @press-enter="changeCurrent(1)"
        ></a-input>
      </a-form-item>

      <a-form-item>
        <a-space>
          <a-button type="primary" size="small" @click="changeCurrent(1)">
            <template #icon>
              <icon-search />
            </template>
            <template #default>查询</template>
          </a-button>
          <a-button size="small" @click="onResetSearch">
            <template #icon>
              <icon-sync />
            </template>
            <template #default>重置</template>
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
    <div class="row_wrap">
      <a-row>
        <a-col :span="6"
          ><a-statistic
            title="申请提现金额"
            :value="pageInfo.totalAmount - 0 || 0"
            show-group-separator
            :animation="true"
            :precision="2"
          >
            <template #prefix>￥</template></a-statistic
          ></a-col
        >
        <a-col :span="6"
          ><a-statistic
            title="已成功打款金额"
            :value="pageInfo.successAmount - 0 || 0"
            show-group-separator
            :animation="true"
            :precision="2"
          >
            <template #prefix>￥</template></a-statistic
          ></a-col
        >
        <a-col :span="6"
          ><a-statistic
            title="打款失败金额"
            :value="pageInfo.failAmount - 0 || 0"
            show-group-separator
            :precision="2"
            :animation="true"
          >
            <template #prefix>￥</template></a-statistic
          ></a-col
        >
        <a-col :span="6"
          ><a-statistic
            title="待打款金额"
            :value="pageInfo.waiteAmount - 0 || 0"
            show-group-separator
            :animation="true"
            :precision="2"
          >
            <template #prefix>￥</template></a-statistic
          ></a-col
        >
      </a-row>
    </div>
    <GiTable
      row-key="id"
      id="fdProcess"
      v-model:columns="columns"
      :loading="loading"
      :data="tableData"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :row-selection="{ type: 'checkbox', showCheckedAll: true }"
      v-model:selectedKeys="selectedKeys"
      :pagination="pagination"
      @refresh="getTableData"
    >
      <template #custom-extra>
        <!-- 
        <a-button type="primary" size="small" v-if="selectedKeys.length > 0" @click="onDeleteBatch(false)">
          <template #icon><icon-delete /></template>
          <span>批量打款</span>
        </a-button>
        <a-button type="primary" size="small" v-if="selectedKeys.length > 0" @click="onDeleteBatch(false)">
          <template #icon><icon-delete /></template>
          <span>批量拒绝</span>
        </a-button> -->
      </template>
      <template #inviteCode="{ record }">
        <MsCopyDiv :text="record.inviteCode" title="邀请码" :showLeftTitle="true" />
        <MsCopyDiv :text="record.mobile" title="手机号" :showLeftTitle="true" />
      </template>
      <template #withdrawalNo="{ record }">
        <MsCopyDiv :text="record.withdrawalNo" title="提现订单号" :showLeftTitle="true" />
        <MsCopyDiv
          :text="record.alipayTradeId"
          title="支付宝交易号"
          :showLeftTitle="true"
          v-if="record.withdrawalAccountInfo.withdrawalMethod != 2"
        />
      </template>
      <template #withdrawalAccountInfo="{ record }">
        <p>
          <!-- <a-button type="text" size="small" @click="onChangeMehtod(record)"
            ><template #icon> <icon-swap /> </template
          ></a-button> -->
          {{ record.withdrawalAccountInfo.withdrawalMethod == 1 ? '支付宝' : '银行卡' }}：
          {{ record.withdrawalAccountInfo.withdrawalName }}
          <MsCopyDiv :text="record.withdrawalAccountInfo.withdrawalAccount" />
        </p>
      </template>
      <template #payAccountInfo="{ record }">
        <MsCopyDiv
          :text="record.payAccountInfo.account"
          :title="record.payAccountInfo.payTypeName"
          :showLeftTitle="true"
        />
      </template>
      <template #statusName="{ record }">
        <p><span :class="'span_color color_' + record.status"></span> {{ record.statusName }}</p>
      </template>
      <template #action="{ record }">
        <a-button type="text" size="small" @click="onPayment(record)" v-if="record.status == 0"> 打款 </a-button>
        <a-button type="text" size="small" @click="onPaymentRefuse(record)" v-if="record.status == 0"> 拒绝 </a-button>
        <a-button type="text" size="small" @click="onDetail(record)"> 详情 </a-button>
      </template>
    </GiTable>
    <PayModal ref="PayModalRef" @getTableData="getTableData"></PayModal>
    <RefuseModal ref="RefuseModalRef" @getTableData="getTableData"></RefuseModal>
    <WithdrawalModal ref="WithdrawalModalRef" @getTableData="getTableData"></WithdrawalModal>
  </div>
</template>

<script setup>
import { Message, Modal } from '@arco-design/web-vue'
import { usePagination } from '@/hooks'
import {
  takeOutPageBatchDelete,
  takeOutPageEdit,
  finance,
  financePageInfo,
  financeAllPaymentMethods,
  financeHandlreFusePay
} from '@/apis'
import PayModal from './PayModal.vue'
import WithdrawalModal from './WithdrawalModal.vue'
import RefuseModal from './RefuseModal.vue'
import { copyText, deleteEmpty } from '@/utils/common'
import ImgHoverPreview from '@/components/ImgHoverPreview/index.vue'
import MsCopyDiv from '@/components/MsCopyDiv/index.vue'
import $bus from '@/utils/bus'
import dayjs from 'dayjs'

defineOptions({ name: 'fdProcess' })

const router = useRouter()

const columns = ref([
  {
    title: '提现用户',
    width: 200,
    slotName: 'inviteCode'
  },
  {
    title: '提现金额',
    width: 140,
    dataIndex: 'withdrawalAmount',
    render: (data) => {
      const text = data.record.withdrawalAmount
      return '￥' + text
    }
  },
  {
    title: '到账金额',
    width: 140,
    dataIndex: 'receiveAmount',
    render: (data) => {
      const text = data.record.receiveAmount
      return '￥' + text
    }
  },
  {
    title: '提现时间',
    width: 180,
    dataIndex: 'withdrawalTime'
  },
  {
    title: '到账时间',
    width: 180,
    dataIndex: 'receiveTime'
  },
  {
    title: '提现凭证',
    width: 320,
    slotName: 'withdrawalNo'
  },
  {
    title: '提现账号',
    width: 200,
    slotName: 'withdrawalAccountInfo'
  },
  {
    title: '打款账户',
    width: 150,
    slotName: 'payAccountInfo'
    // render: (data) => {
    //   return data.record.payAccountInfo.payTypeName + '：' + data.record.payAccountInfo.account
    // }
  },

  {
    title: '状态',
    width: 120,
    slotName: 'statusName'
  },
  {
    title: '备注',
    width: 150,
    dataIndex: 'msg',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '操作',
    width: 120,
    fixed: 'right',
    align: 'center',
    slotName: 'action'
  }
])

const PayModalRef = ref()
const RefuseModalRef = ref()
const WithdrawalModalRef = ref()
const pageInfo = ref({})
const loading = ref(false)
const tableData = ref([])
const selectedKeys = ref([])
const payMethods1 = ref([])

const statusList = [
  {
    id: -2,
    text: '打款失败'
  },
  {
    id: 1,
    text: '打款成功'
  },
  {
    id: 0,
    text: '未审核'
  }
] // 打款状态

const listParams = reactive({
  page: 1,
  pageSize: 10,
  searchValue: '',
  paymethod: undefined, // 1,小额打款 2，灵活用工
  payAccount: undefined, //打款账户
  payType: '0', //打款类型 1支付宝  2银行卡
  status: undefined, // 状态 //是否打款成功 0未审核 1打款成功 -2 打款失败
  submitStartAt: dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD HH:mm:ss'), // 提现开始时间
  submitStartEnd: undefined, // 提现结束时间
  payStartAt: undefined, // 到账开始时间
  payStartEnd: undefined, // 到账结束时间
  withdrawalNo: undefined, // 提现单号
  alipayTradeId: undefined, // 支付宝交易号
  minAmount: undefined, // 最小金额
  maxAmount: undefined, // 最大金额
  keyword: undefined, // 邀请码/手机号
  receiveAccount: undefined, //收款-支付宝/银行卡
  withdrawalType: undefined //提现类型 1支付宝 4灵工银行卡  3 灵工支付宝
})

const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: listParams.pageSize })

const init = () => {
  if (new Date().getDate() < 25) {
    listParams.submitStartAt = dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD HH:mm:ss')
    listParams.submitStartEnd = undefined
  } else {
    listParams.submitStartAt = dayjs().date(25).startOf('date').format('YYYY-MM-DD HH:mm:ss')
    listParams.submitStartEnd = undefined
  }
}
init()
const getPageInfo = async () => {
  const res = await financePageInfo(deleteEmpty(listParams))
  pageInfo.value = res.data
}
getPageInfo()

// 获取列表数据
const getTableData = async () => {
  try {
    loading.value = true
    listParams.page = pagination.current
    listParams.pageSize = pagination.pageSize
    const res = await finance(deleteEmpty(listParams))
    tableData.value = res.data.list
    setTotal(res?.data?.meta?.pagination?.total || 0)
  } finally {
    loading.value = false
  }
}
getTableData()
const mapArrow = (arr, prop) => {
  const grouped = Object.create(null)
  arr.map((item) => {
    const key = item[prop]
    if (!grouped[key]) {
      grouped[key] = []
    }
    grouped[key].push(item)
  })
  return grouped
}
const fieldNames = { value: 'id', label: 'account' }
const getPayMethods = async () => {
  const res = await financeAllPaymentMethods()
  res.data.list = res.data.list.map((o) => {
    return {
      account: o.account /* + '（' + ['支付宝', '银行卡'][o.accountType - 1] + '）' */,
      id: o.id,
      method: o.method
    }
  })
  payMethods1.value = [
    {
      id: 1,
      account: '小额打款',
      children: mapArrow(res.data.list, 'method')['1']
    },
    {
      id: 2,
      account: '灵活用工',
      children: mapArrow(res.data.list, 'method')['2']
    }
  ]
  console.log(payMethods1.value)
}
getPayMethods()

// 添加/编辑
const onDetail = (item, copy = false) => {
  router.push({
    name: 'processDetail',
    query: { userId: item?.userId, id: item?.id },
    state: item ? { item: JSON.stringify({ ...item, copy }) } : undefined
  })
}
// 拒绝打款
const onPaymentRefuse = async (item) => {
  RefuseModalRef.value?.openModal(item)
  // await new Promise((resolve, reject) => {
  //   financeHandlreFusePay({ userBalanceWithdrawalId: item.id, remark: item.remark })
  //     .then(() => {
  //       Message.success('操作成功')
  //       getTableData()
  //       resolve(true)
  //     })
  //     .catch(() => {
  //       reject()
  //     })
  // })
}
// 打款
const onPayment = (item) => {
  PayModalRef.value?.openModal(item)
}
// 更改提现账户
const onChangeMehtod = (item) => {
  WithdrawalModalRef.value?.openModal(item)
}

const topRefresh = () => {
  getPageInfo()
  getTableData()
}

// 删除数据
const onDeleteBatch = async (id) => {
  Modal.warning({
    title: '提示',
    content: '是否确认删除？',
    hideCancel: false,
    onOk: () => {
      loading.value = true
      const ids = id ? [id] : selectedKeys.value
      // takeOutPageBatchDelete({ ids: ids.join(',') })
      //   .then(() => {
      //     Message.success('删除成功')
      //     getTableData()
      //   })
      //   .finally(() => {
      //     loading.value = false
      //   })
    }
  })
}

// 表格页码改变
const changeCurrent = (e) => {
  pagination.current = listParams.page = e
  getTableData()
  getPageInfo()
}

// 列表重置搜索
const onResetSearch = () => {
  listParams.paymethod =
    listParams.payAccount =
    listParams.status =
    listParams.payStartAt =
    listParams.payStartEnd =
    listParams.withdrawalNo =
    listParams.alipayTradeId =
    listParams.minAmount =
    listParams.maxAmount =
    listParams.keyword =
    listParams.receiveAccount =
      undefined

  // listParams.submitStartAt = dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD HH:mm:ss') // 提现开始时间
  // listParams.submitStartEnd = undefined // 提现结束时间
  init()
  listParams.payType = '0'
  changeCurrent(1)
}

onMounted(() => {
  $bus.on('fdProcess', () => {
    getTableData()
  })
})

onUnmounted(() => {
  $bus.off('fdProcess')
})
</script>

<style lang="scss" scoped>
.table2 {
  height: 100%;
  overflow: hidden;
  // margin: $margin;
  padding: $margin;

  padding-bottom: $padding;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  :deep(.arco-row) {
    width: 100%;
  }
  .form {
    background: var(--color-bg-1);
    padding: $margin;
    :deep(.arco-form-item) {
      margin-bottom: 10px;
    }
  }
  .row_wrap {
    background: var(--color-bg-1);
    padding: $margin;
    margin-bottom: $margin;
    text-align: center;
    .arco-col {
      position: relative;
      &:not(:last-child):after {
        position: absolute;
        content: '';
        right: 0;
        top: 50%;
        transform: translate(0%, -50%);
        width: 1px;
        height: 30px;
        background: #eee;
      }
    }
    span {
      display: inline-block;
      margin: 10px 0;
      color: rgba(32, 32, 32, 1);
    }
  }
  .gi-table {
    background: var(--color-bg-1);
    padding: $margin;
  }

  .span_color {
    display: inline-block;
    width: 5px;
    height: 5px;
    border-radius: 50%;
    &.color_-2 {
      background: rgba(186, 186, 186, 1);
    }
    &.color_1 {
      background: rgba(59, 201, 105, 1);
    }
    &.color_0 {
      background: rgba(245, 121, 23, 1);
    }
  }
}
</style>
